﻿using Serilog;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WinForm.NET4.Sample.Extensions
{
    public static class EnricherExtensions
    {
        public static LoggerConfiguration WithLoginInfo(this LoggerEnrichmentConfiguration enrich)
        {
            if (enrich == null)
                throw new ArgumentNullException(nameof(enrich));

            return enrich.With<LoginInfoEnricher>();
        }
    }
    public class LoginInfoEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var appContext = IdentityContext.Current;
            if (null != appContext)
            {
                //写自定义的user 信息到log
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserId", appContext.UserId));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserName", appContext.UserName));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserType", appContext.UserType));

            }
        }
    }
}
